<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import '@/assets/css/global.css'

// 接受来自父组件的数据
const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
  columns: {
    type: Array,
    required: true,
    default: () => [],
  },
})

// 给父组件发送数据
const emit = defineEmits(['update:data'])

// 响应式状态
const currentPage = ref(1)
const pageSize = ref(5)
const sortedColumn = ref(null)
const sortDirection = ref('asc')

// 分页数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  console.log('开始：', start)
  return sortedData.value.slice(start, start + pageSize.value)
})

const totalPages = computed(() => {
  return Math.ceil(sortedData.value.length / pageSize.value)
})

// 排序后的数据
const sortedData = computed(() => {
  if (sortedColumn.value) {
    return [...props.data].sort((a, b) => {
      const valA = a[sortedColumn.value]
      const valB = b[sortedColumn.value]
      if (typeof valA === 'number' && typeof valB === 'number') {
        return sortDirection.value === 'asc' ? valA - valB : valB - valA
      } else {
        return sortDirection.value === 'asc'
          ? String(valA).localeCompare(String(valB))
          : String(valB).localeCompare(String(valA))
      }
    })
  }
  return props.data
})

// 分页方法
const prevPage = () => {
  currentPage.value = Math.max(1, currentPage.value - 1)
}

const nextPage = () => {
  currentPage.value = Math.min(totalPages.value, currentPage.value + 1)
}

const updatePageSize = () => {
  currentPage.value = 1
}

// 排序方法
const sortByColumn = (key) => {
  if (sortedColumn.value === key) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortedColumn.value = key
    sortDirection.value = 'asc'
  }
}

// 编辑方法
const saveEdit = (rowIndex, key, event) => {
  const newData = [...sortedData.value]
  newData[rowIndex][key] = event.target.textContent
  emit('update:data', newData)
}
</script>

<template>
  <div class="simple-table">
    <!-- 表格 -->
    <table>
      <thead>
        <tr>
          <th
            v-for="column in columns"
            :key="column.key"
            @click="sortByColumn(column.key)"
            :class="{ sorted: sortedColumn === column.key }"
            :style="{ width: column.width }"
          >
            {{ column.label }}
            <span
              v-if="sortedColumn === column.key"
              :class="sortDirection === 'asc' ? 'asc' : 'desc'"
            >
              {{ sortDirection === 'asc' ? '↑' : '↓' }}
            </span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, rowIndex) in paginatedData" :key="rowIndex">
          <td
            v-for="column in columns"
            :key="column.key"
            :contenteditable="column.editable"
            @blur="saveEdit(rowIndex, column.key, $event)"
            :style="{ width: column.width }"
          >
            {{ row[column.key] }}
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
      <select v-model="pageSize" @change="updatePageSize">
        <option>5</option>
        <option>10</option>
        <option>20</option>
      </select>
    </div>
  </div>
</template>

<style scoped>
* {
  color: var(--text-color);
}
.simple-table {
  border: 2px solid var(--border-color);
  /* width: 100%; */
  padding: 5px;
}

table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 12px;
  border-bottom: 1px solid var(--border-color-bottom);
  text-align: left;
}

th {
  cursor: pointer;
}

th.sorted {
  font-weight: bolder;
}

th span {
  margin-left: 5px;
}

.pagination {
  margin-top: 10px;
  text-align: center;
}

/* 选择所有具有 contenteditable 属性的 <td> 元素 */
td[contenteditable] {
  outline: none;
  border: 2px;
  background-color: var(--bgc-table-selected);
}

@media (max-width: 430px) {
  /* 修复后代码，添加了选择器 body 作为标识符 */
  body {
    font-size: 2.5vw;
  }

  .simple-table {
    font-size: 2.5vw;
  }

  table {
    font-size: 2.5vw;
  }

  th,
  td {
    font-size: 2.5vw;
  }

  .pagination {
    font-size: 2.5vw;
  }
}
</style>
